package com.crm.controller;

import java.io.IOException;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * 待办任务controller
 * @author 梁箐
 *
 */
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.crm.model.mpojo.Care;
import com.crm.model.mpojo.Tasks;
import com.crm.model.pojo.Customer;
import com.crm.model.pojo.Dictionary;
import com.crm.model.pojo.Task;
import com.crm.services.CareServices;
import com.crm.services.ContactServices;
import com.crm.services.CustomerServices;
import com.crm.services.DictionaryServices;
import com.crm.services.RepairServices;
import com.crm.services.TaskServices;
import com.crm.services.UserServices;
import com.crm.util.LoginUtil;
import com.github.pagehelper.PageInfo;
@Controller
@RequestMapping("/aftersale")
public class TaskController {
	
	@Autowired
	TaskServices taskServices;
	@Autowired
	UserServices userservices;
	@Autowired
	CustomerServices customerServices;
	@Autowired
	DictionaryServices dictionaryServices;
	@Autowired
	ContactServices contactServices;
	@Autowired
	RepairServices repairServices;
	@Autowired
	CareServices careServices;
	
	/**
	 * 分页查询待办任务
	 * 
	 * @return
	 */
	@GetMapping("/task")
	public ModelAndView findtask(Integer pageNum, Integer pageSize,Integer statueID,String search) {
		if (pageNum == null)
			pageNum = 1;
		if (pageSize == null)
			pageSize = 6;
		ModelAndView mv = new ModelAndView("aftersale/task");
		System.out.println("待办任务！");
		// 查询待办任务
		List<Map<String, String>> selectPage = taskServices.selectPage(pageNum, pageSize,statueID, search);
		System.out.println(selectPage);
		String jsonString = JSONObject.toJSONString(selectPage);
		// 获取分页信息
		PageInfo<Map<String, String>> page = new PageInfo<Map<String, String>>(selectPage);
		System.out.println(page);
		String pageInfo = JSONObject.toJSONString(page);
		System.out.println(page);
		mv.addObject("list", jsonString);
		mv.addObject("page", page);
		mv.addObject("pageinfo", pageInfo);
		return mv;
	}
	
	/**
	 * 分页查询获取qa（刷新表单）
	 * @param pageNum
	 * @param pageSize
	 * @param statueID
	 * @param search
	 * @return
	 */
	@PostMapping("/task")
	@ResponseBody	
	public PageInfo<Map<String, String>> findtaskNew(Integer pageNum, Integer pageSize,Integer statueID,String search) {
		if (pageNum == null)
			pageNum = 1;
		if (pageSize == null)
			pageSize = 6;
		//分页查询qa
		System.out.println("Task:"+pageNum+"\t"+pageSize+"\t"+statueID+"\t"+search);
		List<Map<String, String>> selectPage = taskServices.selectPage(pageNum, pageSize, statueID, search);
		//获取分页信息
		PageInfo<Map<String, String>> page = new PageInfo<Map<String, String>>(selectPage);
		return page;
	}

	
	/**
	 * id逻辑删除
	 * 
	 * @param taskid
	 * @return
	 */
	@PostMapping("/deleteonetask")
	@ResponseBody
	public JSONObject deleteone(@RequestParam("ID") Integer taskid) {
		System.out.println("删除单个:" + taskid);
		JSONObject jsonObject = new JSONObject();
		Map<String, String> selectOneByid = taskServices.selectOneByid(taskid);
		String status = String.valueOf(selectOneByid.get("status"));
		if (status.equals("1427")||status.equals("1429")) {
			taskServices.deleteByStatue(taskid);
		} else if (status==null || status=="" || "null".equals(status)) {
			taskServices.deleteByStatue(taskid);
		}else {
			jsonObject.put("status", status);
		}
		return jsonObject;
	}
	
	/**
	 * 根据用户编号查询联系人和维修单
	 * 
	 * @param conName
	 */
	@RequestMapping("/custToconfortask")
	@ResponseBody
	public JSONObject selectcusttocon(@RequestParam("custid") Integer custid) {
		//客户编号查询联系人
		List<Map<String, String>> selectcustTocon = contactServices.selectcustTocon(custid);
		//客户编号查询维修单
		List<Map<String, String>> selectcustToRepire = repairServices.selectcustToRepire(custid);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("contID", selectcustTocon);// 联系人
		jsonObject.put("repaireID", selectcustToRepire);// 维修工单人
		return jsonObject;
	}
	
	
	/**
	 * 新增时查询对应可选数据
	 * @return
	 */
	@RequestMapping("/chooseTaskOptions")
	@ResponseBody
	public JSONObject addOptionts() {
		// 查询所有客户
		List<Map<String, String>> allCustomerName = customerServices.selectAllCustomer();
		System.out.println("客户名：" + allCustomerName);	
		//查询任务分类
		List<Dictionary> findByDictParentid = dictionaryServices.findByDictParentid(1331);
		System.out.println("任务分类：" + findByDictParentid);
		//查询执行人
		List<Map<String, String>> allusername = userservices.selectUserAll();
		System.out.println("执行人:" + allusername);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("comcustid", allCustomerName);//客户
		jsonObject.put("taskclassity", findByDictParentid);//任务分类
		jsonObject.put("doname", allusername);//执行人
		jsonObject.put("user", LoginUtil.getUser());//执行人
		return jsonObject;
		
	}
	
	/**
	 * 新增待办任务
	 * @param description
	 * @param cust
	 * @param contact
	 * @param repair
	 * @param classity
	 * @param taskdate
	 * @param domanID
	 * @return
	 */
	@RequestMapping("/addOnetask")
	@ResponseBody
	public String addTask(@RequestParam(name = "description",required = false) String description,
			@RequestParam(name = "custID",required = false) Integer cust,
			@RequestParam(name = "contID",required = false) Integer contact,
			@RequestParam(name = "repairID",required = false) Integer repair,
			@RequestParam(name = "taskclassity",required = false) Integer classity,
			@RequestParam(name = "taskdate",required = false) String taskdate,
			@RequestParam(name = "doname",required =false) Integer domanID) {
		// 转换日期格式
		java.sql.Date date = java.sql.Date.valueOf(taskdate.substring(0, 10));
		System.out.println(date);
		//获取本地时间
		Time time = java.sql.Time.valueOf(getTime());
		System.out.println(time);
		//实例化对象
		Task task = new Task();
		Customer findByCust = customerServices.findByCustIdPage(cust);
		task.setCustomer(findByCust);//客户
		task.setConid(contact);//联系人
		task.setTaskManclassify(classity);//类型
		task.setTaskDescription(description);;//描述
		task.setTaskDate(date);//日期
		task.setTaskTime(time);//时间
		task.setCreatDate(java.sql.Date.valueOf(getDate()));//任务创建时间
		task.setCreateMan(domanID);//创建人（当前登录用户）
		task.setTask_manID(domanID);//执行人
		task.setDeletstatue(1206);//状态
		task.setTaskPriority(1361);//默认优先级
		task.setTaskStatus(1428);//设置任务执行状态（执行中）
		//添加一个待办任务
		taskServices.addTask(task);
		System.out.println("添加："+taskServices.addTask(task));
		return "添加！";
	}
	
	/**
	 * 根据编号查询单条
	 * @return
	 */
	@RequestMapping("/selectOnetask")
	@ResponseBody
	public JSONObject selectOneTask(@RequestParam("ID") Integer taskid) {
		// 查询所有客户
		List<Map<String, String>> allCustomerName = customerServices.selectAllCustomer();
		System.out.println("客户名：" + allCustomerName);	
		//查询任务分类
		List<Dictionary> findByDictParentid = dictionaryServices.findByDictParentid(1331);
		System.out.println("任务分类：" + findByDictParentid);
		//查询执行人
		List<Map<String, String>> allusername = userservices.selectUserAll();
		System.out.println("执行人:" + allusername);
		/*// 查询任务状态
		List<Dictionary> taskstatus = dictionaryServices.findByDictParentid(1426);
		System.out.println("任务状态：" + taskstatus);
		// 查询优先级
		List<Dictionary> taskpriority = dictionaryServices.findByDictParentid(1360);
		System.out.println("优先级：" + taskstatus);*/
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("comcust", allCustomerName);//客户
		jsonObject.put("taskclassity", findByDictParentid);//任务分类
		jsonObject.put("doname", allusername);//执行人
		/*jsonObject.put("taskstatus", taskstatus);//任务状态
		jsonObject.put("taskpriority", taskpriority);//优先级*/
		//根据待办任务编号查询单条
		Map<String, String> oneTask = taskServices.selectOneByid(taskid);
		jsonObject.put("onetask", oneTask);
		//根据编号查询待办任务
		System.out.println("任务编号："+taskid);
		Task findByid = taskServices.findByid(taskid);
		//根据客户编号查询联系人
		List<Map<String, String>> contact = contactServices.selectcustTocon(findByid.getCustomer().getCustId());
		System.out.println("联系人："+contact);
		//根据kehu编号查询维修工单
		List<Map<String, String>> repire = repairServices.selectcustToRepire(findByid.getCustomer().getCustId());
		jsonObject.put("contact", contact);//联系人
		jsonObject.put("repire", repire);//维修工单
		return jsonObject;
	}
	
	/**
	 * 修改待办任务
	 * @param taskid
	 * @param description
	 * @param cust
	 * @param contact
	 * @param repair
	 * @param classity
	 * @param taskdate
	 * @param domanID
	 * @return
	 */
	@RequestMapping("/updateOnetask")
	@ResponseBody
	public String updateTask(@RequestParam("ID") Integer taskid,
			@RequestParam(name = "description",required = false) String description,
			@RequestParam(name = "custID",required = false) Integer cust,
			@RequestParam(name = "conID",required = false) Integer contact,
			@RequestParam(name = "repairID",required = false) Integer repair,
			@RequestParam(name = "taskclassity",required = false) Integer classity,
			@RequestParam(name = "priority",required = false) Integer priority,
			@RequestParam(name = "status",required = false) Integer status,
			@RequestParam(name = "taskdate",required = false) String taskdate,
			@RequestParam(name = "doname",required =false) Integer domanID) {
		// 转换日期格式
		java.sql.Date date = java.sql.Date.valueOf(taskdate.substring(0, 10));
		System.out.println(date);
		//获取本地时间
		Time time = java.sql.Time.valueOf(getTime());
		System.out.println(time);
		//实例化对象
		Tasks task = new Tasks();
		task.setTaskId(taskid);//待办任务编号
		task.setCustId(cust);;//客户
		task.setConId(contact);//联系人
		task.setTaskClassify(classity);//类型
		task.setTaskDescription(description);;//描述
		task.setTaskDate(date);//日期
		task.setTaskTime(time);//时间
		task.setCreatMan(domanID);//执行人
		task.setDeletstatue(1206);//状态
		task.setTaskPriority(priority);//优先级
		task.setTaskStatus(status);//设置任务执行状态
		taskServices.updateTasks(task);
		//根据待办任务自动生成客户关怀(任务完成)
		if (status==1427) {
			Care care = new Care();
			//根据任务id查询单条
			Map<String, String> selectOneByid = taskServices.selectOneByid(taskid);
			care.setCustId(Integer.parseInt(String.valueOf(selectOneByid.get("custid"))));//关怀客户
			care.setCareConid(Integer.parseInt(String.valueOf(selectOneByid.get("conid"))));//关怀联系人
			care.setCareUserid(Integer.parseInt(String.valueOf(selectOneByid.get("manID"))));//关怀执行人
			care.setCareTheme(selectOneByid.get("description"));//关怀主题
			care.setCareDate(java.sql.Date.valueOf(String.valueOf(selectOneByid.get("taskdate"))));//关怀日期
			care.setCareClassity(1073);//关怀分类
			care.setCareStatue(1283);//关怀状态
			careServices.addCares(care);
			System.out.println("自动生成客户关怀："+careServices.addCares(care));
		}
		return "修改！";
	}

	/**
	 * 导出
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "taskExcelDownloads", method = RequestMethod.GET)
    public void downloadAllClassmate(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("待办任务！");

        List<Map<String, String>> selectAll = taskServices.selectAllInfo();
      
        String fileName = "taskinfo"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据

        int rowNum = 1;

        String[] headers = { "编号", "主题","任务执行状态", "优先级", "客户","开始时间","执行人","状态"};
        //headers表示excel表中第一行的表头

        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头

        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Map<String, String> map : selectAll) {
        	HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(String.valueOf(map.get("ID")));
            row1.createCell(1).setCellValue(String.valueOf(map.get("description")));
            row1.createCell(2).setCellValue(String.valueOf(map.get("taskstatue")));
            row1.createCell(3).setCellValue(map.get("taskpriority"));
            row1.createCell(4).setCellValue(map.get("custname"));
            row1.createCell(5).setCellValue(map.get("taskdate"));
            row1.createCell(6).setCellValue(map.get("taskdoman"));
            row1.createCell(7).setCellValue(map.get("deletstatue"));
            rowNum++;
      		}
              
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

	
	//获取本地时间(时分秒)
	public String getTime() {
		Calendar now = Calendar.getInstance();
		System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));
		System.out.println("分: " + now.get(Calendar.MINUTE));
		System.out.println("秒: " + now.get(Calendar.SECOND));
		System.out.println("当前时间毫秒数：" + now.getTimeInMillis());
		System.out.println(now.getTime());
		Date d = new Date();
		System.out.println(d);
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		String dateNowStr = sdf.format(d);
		return dateNowStr;
	}
	
	//获取本地时间(年月日)
	public String getDate() {
		Calendar now = Calendar.getInstance();
		System.out.println("年: " + now.get(Calendar.YEAR));
		System.out.println("月: " + (now.get(Calendar.MONTH) + 1) + "");
		System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));
		Date d = new Date();
		System.out.println(d);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dateNowStr = sdf.format(d);
		return dateNowStr;
	}
	
}
